package br.ufrj.dcc.trabxml.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import br.ufrj.dcc.trabxml.manager.BookManager;
import br.ufrj.dcc.trabxml.util.Properties;
import br.ufrj.dcc.trabxml.view.FormMain;

public class ReturnBook implements ActionListener {
    
    private FormMain form;
    
    public ReturnBook (FormMain form) {
        this.form = form;
    }

    public void actionPerformed(ActionEvent e) {
        int myGroup = Integer.parseInt(Properties.instance.getProperty("mygroup"));
        int owner = form.getLendOwner();
        String isbn = form.getLendISBN();
        try {
            BookManager manager = new BookManager();    
            String xml = manager.getControlXML();
            int to = manager.getActualGroup(xml,owner, isbn);
            int from = manager.getLastGroup(xml, owner, isbn);
            if (to != myGroup) { //pegando o livro de volta
                manager.takeBookBack(to, owner, isbn);
                JOptionPane.showMessageDialog(form, "Livro devolvido com sucesso.", "Info",
                        JOptionPane.INFORMATION_MESSAGE);                
            }        
            if (from != myGroup) {//eu devolvendo o livro dos outros
                if (to != myGroup) {//se eu tive que pegar de volta
                    if (JOptionPane.showConfirmDialog(form, "Deseja tambem devolver este livro ao grupo "+from+"?","Devolver?",JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
                        return;
                    }
                }
                manager.returnBook(owner, isbn);
                JOptionPane.showMessageDialog(form, "Livro devolvido com sucesso.", "Info",
                        JOptionPane.INFORMATION_MESSAGE);
                form.setLendISBN(null);//Soh eh nulo qdo o livro nao estah mais comigo                
            }             
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(form, ex.getMessage(), "Erro",
                    JOptionPane.ERROR_MESSAGE);                
        }
    }

}
